<template>
  <div v-if="isVisible" class="patrol-route">
    <!-- 巡检控制中心 -->
    <div class="patrol-control-panel">
      <div class="panel-header">
        <h3>
          <svg class="header-icon" viewBox="0 0 24 24">
            <path
              d="M12,2A2,2 0 0,1 14,2A2,2 0 0,1 16,4V8A2,2 0 0,1 14,10H10A2,2 0 0,1 8,8V4A2,2 0 0,1 10,2H12M10,4V8H14V4H10M12,10A6,6 0 0,1 18,16V18A2,2 0 0,1 16,20H8A2,2 0 0,1 6,18V16A6,6 0 0,1 12,10M12,12A4,4 0 0,0 8,16V18H16V16A4,4 0 0,0 12,12Z"
              fill="currentColor" />
          </svg>
          巡检控制中心
        </h3>
      </div>

      <div class="panel-content">
        <!-- 计划选择 -->
        <div class="plan-selector">
          <label>选择巡检计划：</label>
          <select v-model="selectedPlan" @change="onPlanChange">
            <option v-for="plan in patrolPlans" :key="plan.id" :value="plan.id">
              {{ plan.name }}
            </option>
          </select>
        </div>

        <!-- 计划详情 -->
        <div v-if="currentPlan" class="plan-details">
          <div class="plan-info">
            <div class="plan-title">
              <h4>{{ currentPlan.name }}</h4>
              <span class="priority-badge" :style="{ backgroundColor: priorityColors[currentPlan.priority] }">
                {{ currentPlan.priority === 'high' ? '高优先级' : currentPlan.priority === 'medium' ? '中优先级' : '低优先级' }}
              </span>
            </div>
            <p class="plan-description">{{ currentPlan.description }}</p>

            <div class="plan-stats">
              <div class="stat-item">
                <div class="stat-label">巡检周期</div>
                <div class="stat-value">{{ currentPlan.cycle }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">设备数量</div>
                <div class="stat-value">{{ currentPlan.deviceCount }}</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">预计时长</div>
                <div class="stat-value">{{ currentPlan.estimatedDuration }}</div>
              </div>
            </div>
          </div>

          <!-- 巡检点列表 -->
          <div class="checkpoints-list">
            <h5>巡检路线 ({{ currentPlan.checkpoints.length }}个检查点)</h5>
            <div class="checkpoints-grid">
              <div v-for="(checkpoint, index) in currentPlan.checkpoints" :key="checkpoint.id" class="checkpoint-item">
                <div class="checkpoint-number">{{ index + 1 }}</div>
                <div class="checkpoint-info">
                  <div class="checkpoint-name">{{ checkpoint.name }}</div>
                  <div class="checkpoint-type">{{ checkpoint.deviceType }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { priorityColors,checkpointIcons, getTransformedCheckpoints } from './patrolData.js'
import api from '@/api'

import useDataStore from '@/stores/data.js'
import { storeToRefs } from 'pinia'
const store = useDataStore()
const { patrolPlans } = storeToRefs(store)

const props = defineProps({
  mapInstance: Object,
  isVisible: Boolean
})


// 响应式数据
const selectedPlan = ref('')
const currentPlan = computed(() => {
  return patrolPlans.value.find(plan => plan.id === selectedPlan.value) || null
})

// 地图元素引用
const routePolyline = ref(null)
const checkpointMarkers = ref([])
const patrollerMarker = ref(null) // 巡检员标记
const patrolAnimation = ref(null) // 动画控制
const isPatrolling = ref(false) // 巡检状态

// 获取巡检点图标
const getCheckpointIcon = (type) => {
  return checkpointIcons[type]?.icon || '📍'
}

// 选择计划变化处理
const onPlanChange = () => {
  if (selectedPlan.value && props.mapInstance) {
    nextTick(() => {
      drawPatrolRoute()
    })
  } else {
    clearMap()
  }
}

// 创建巡检员标记
const createPatrollerMarker = () => {
  const svg = `
    <svg width="60" height="60" viewBox="0 0 60 60" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <filter id="glow" x="-30%" y="-30%" width="160%" height="160%">
          <feGaussianBlur stdDeviation="3" result="coloredBlur"/>
          <feMerge> 
            <feMergeNode in="coloredBlur"/>
            <feMergeNode in="SourceGraphic"/>
          </feMerge>
        </filter>
        <radialGradient id="backgroundGradient" cx="50%" cy="50%" r="50%">
          <stop offset="0%" style="stop-color:rgba(82, 183, 136, 0.4);stop-opacity:1" />
          <stop offset="100%" style="stop-color:rgba(82, 183, 136, 0.1);stop-opacity:1" />
        </radialGradient>
      </defs>
      <!-- 背景圆形 -->
      <circle cx="30" cy="30" r="28" fill="url(#backgroundGradient)" stroke="#52b788" stroke-width="3" filter="url(#glow)"/>
      <!-- 巡检员小人 -->
      <g transform="translate(30, 30)" fill="#52b788">
        <!-- 头部 -->
        <circle cx="0" cy="-10" r="4.5" fill="#52b788" stroke="#ffffff" stroke-width="1"/>
        <!-- 身体 -->
        <rect x="-2.5" y="-5" width="5" height="12" fill="#52b788" stroke="#ffffff" stroke-width="0.5"/>
        <!-- 左臂 -->
        <rect x="-6" y="-2" width="4" height="2.5" fill="#52b788" stroke="#ffffff" stroke-width="0.5"/>
        <!-- 右臂 -->
        <rect x="2" y="-2" width="4" height="2.5" fill="#52b788" stroke="#ffffff" stroke-width="0.5"/>
        <!-- 左腿 -->
        <rect x="-3" y="7" width="2.5" height="7" fill="#52b788" stroke="#ffffff" stroke-width="0.5"/>
        <!-- 右腿 -->
        <rect x="0.5" y="7" width="2.5" height="7" fill="#52b788" stroke="#ffffff" stroke-width="0.5"/>
        <!-- 帽子 -->
        <rect x="-3" y="-16" width="6" height="3" fill="#52b788" stroke="#ffffff" stroke-width="0.5"/>
      </g>
      <!-- 脉冲动画 -->
      <circle cx="30" cy="30" r="24" fill="none" stroke="#52b788" stroke-width="2" opacity="0.8">
        <animate attributeName="r" values="24;32;24" dur="2s" repeatCount="indefinite"/>
        <animate attributeName="opacity" values="0.8;0.2;0.8" dur="2s" repeatCount="indefinite"/>
      </circle>
    </svg>
  `
  return svg
}

// 开始巡检动画
const startPatrolAnimation = (route) => {
  if (!props.mapInstance || !route || route.length < 2) return

  stopPatrolAnimation() // 停止之前的动画

  isPatrolling.value = true

  // 创建巡检员标记
  if (!patrollerMarker.value) {
    patrollerMarker.value = new window.AMap.Marker({
      content: createPatrollerMarker(),
      position: route[0], // 从第一个点开始
      offset: new window.AMap.Pixel(-30, -30),
      zIndex: 200
    })
    props.mapInstance.add(patrollerMarker.value)
  }

  // 动画参数
  let currentSegment = 0
  let progress = 0
  const speed = 0.002 // 控制移动速度，值越小越慢

  const animate = () => {
    if (!isPatrolling.value || !patrollerMarker.value) return

    const startPoint = route[currentSegment]
    const endPoint = route[currentSegment + 1]

    if (!startPoint || !endPoint) {
      // 到达终点，重新开始循环
      currentSegment = 0
      progress = 0
      if (route.length > 1) {
        patrollerMarker.value.setPosition(route[0])
        requestAnimationFrame(animate)
      }
      return
    }

    // 线性插值计算当前位置
    const currentLng = startPoint[0] + (endPoint[0] - startPoint[0]) * progress
    const currentLat = startPoint[1] + (endPoint[1] - startPoint[1]) * progress

    // 更新巡检员位置
    patrollerMarker.value.setPosition([currentLng, currentLat])

    // 更新进度
    progress += speed

    if (progress >= 1) {
      // 到达当前段终点，移动到下一段
      currentSegment++
      progress = 0
    }

    patrolAnimation.value = requestAnimationFrame(animate)
  }

  // 开始动画
  animate()
}

// 停止巡检动画
const stopPatrolAnimation = () => {
  isPatrolling.value = false

  if (patrolAnimation.value) {
    cancelAnimationFrame(patrolAnimation.value)
    patrolAnimation.value = null
  }
}

// 绘制巡检路线
const drawPatrolRoute = () => {
  if (!props.mapInstance || !currentPlan.value) return

  clearMap()

  const AMap = window.AMap
  if (!AMap) return

  try {
    // 获取转换后的巡检点坐标
    const transformedCheckpoints = getTransformedCheckpoints(currentPlan.value)
    const coordinates = transformedCheckpoints.map(checkpoint => [
      checkpoint.transformedCoordinates.lng,
      checkpoint.transformedCoordinates.lat
    ])

    // 绘制路线（连接所有巡检点）
    routePolyline.value = new AMap.Polyline({
      path: coordinates,
      strokeColor: '#52b788',
      strokeWeight: 4,
      strokeStyle: 'dashed',
      strokeDasharray: [10, 5],
      strokeOpacity: 0.8,
      strokeLineCap: 'round',
      zIndex: 100
    })

    props.mapInstance.add(routePolyline.value)

    // 绘制巡检点标记
    transformedCheckpoints.forEach((checkpoint, index) => {
      // 创建巡检点标记
      const marker = new AMap.Marker({
        position: [checkpoint.transformedCoordinates.lng, checkpoint.transformedCoordinates.lat],
        content: createCheckpointMarker(checkpoint, index + 1),
        offset: new AMap.Pixel(-16, -16),
        zIndex: 110
      })

      // 添加点击事件
      marker.on('click', () => {
        showCheckpointInfo(checkpoint, index + 1)
      })

      checkpointMarkers.value.push(marker)
      props.mapInstance.add(marker)
    })

    // 调整地图视野以包含所有巡检点
    if (coordinates.length > 0) {
      // 设置更大的padding，并同时限制最大缩放级别避免两次缩放
      props.mapInstance.setFitView(checkpointMarkers.value, false, [120, 120, 120, 120], 14)

      // 只有在有选择巡检计划的情况下才启动巡检员动画
      setTimeout(() => {
        if (selectedPlan.value) {
          startPatrolAnimation(coordinates)
        }
      }, 200)
    }

  } catch (error) {
    console.error('绘制巡检路线失败:', error)
  }
}

// 创建巡检点标记
const createCheckpointMarker = (checkpoint, number) => {
  const iconColor = getCheckpointColor(checkpoint.type)

  return `
    <div class="checkpoint-marker" style="background: ${iconColor}">
      <div class="checkpoint-number-badge">${number}</div>
      <div class="checkpoint-icon-badge">${getCheckpointIcon(checkpoint.type)}</div>
    </div>
  `
}

// 获取巡检点颜色
const getCheckpointColor = (type) => {
  const colors = {
    security: '#e74c3c',
    emergency: '#f39c12',
    fire: '#e67e22',
    environment: '#27ae60',
    power: '#9b59b6',
    access: '#34495e',
    transport: '#3498db',
    service: '#1abc9c',
    parking: '#95a5a6',
    lighting: '#f1c40f',
    communication: '#8e44ad',
    waste: '#7f8c8d',
    control: '#2c3e50'
  }
  return colors[type] || '#52b788'
}

// 显示巡检点信息
const showCheckpointInfo = (checkpoint, number) => {
  const infoWindow = new window.AMap.InfoWindow({
    content: `
      <div class="checkpoint-info-popup">
        <div class="popup-header">
          <span class="popup-number">${number}</span>
          <h4>${checkpoint.name}</h4>
        </div>
        <div class="popup-content">
          <p><strong>设备类型：</strong>${checkpoint.deviceType}</p>
          <p><strong>检查内容：</strong>${checkpoint.description}</p>
          <p><strong>坐标位置：</strong>${checkpoint.transformedCoordinates.lng.toFixed(6)}, ${checkpoint.transformedCoordinates.lat.toFixed(6)}</p>
        </div>
      </div>
    `,
    offset: new window.AMap.Pixel(0, -30)
  })

  infoWindow.open(props.mapInstance, [checkpoint.transformedCoordinates.lng, checkpoint.transformedCoordinates.lat])
}

// 清理地图元素
const clearMap = () => {
  if (!props.mapInstance) return

  // 停止巡检动画
  stopPatrolAnimation()

  // 清除路线
  if (routePolyline.value) {
    props.mapInstance.remove(routePolyline.value)
    routePolyline.value = null
  }

  // 清除巡检点标记
  if (checkpointMarkers.value.length > 0) {
    checkpointMarkers.value.forEach(marker => {
      props.mapInstance.remove(marker)
    })
    checkpointMarkers.value = []
  }

  // 清除巡检员标记
  if (patrollerMarker.value) {
    props.mapInstance.remove(patrollerMarker.value)
    patrollerMarker.value = null
  }
}


// 监听可见性变化
watch(() => props.isVisible, (newVal) => {
  if (newVal) {
    // 进入巡检模式时默认显示第一个巡检计划
    if (patrolPlans.value.length > 0) {
      selectedPlan.value = patrolPlans.value[0].id
      console.log('巡检模式：默认选择计划', patrolPlans.value[0].name)
      nextTick(() => {
        drawPatrolRoute()
      })
    }
  } else if (!newVal) {
    clearMap()
    // 退出巡检模式时重置选择，但不设为空字符串
    selectedPlan.value = patrolPlans.value.length > 0 ? patrolPlans.value[0].id : ''
  }
}, { immediate: true })

// 监听地图实例变化
watch(() => props.mapInstance, (newMapInstance) => {
  if (newMapInstance && props.isVisible && selectedPlan.value) {
    nextTick(() => {
      drawPatrolRoute()
    })
  }
})


// 组件挂载时初始化
onMounted(() => {
  // 确保初始化时设置默认选择
  if (props.isVisible && patrolPlans.value.length > 0 && !selectedPlan.value) {
    selectedPlan.value = patrolPlans.value[0].id
  }
})

// 组件卸载时清理
onUnmounted(() => {
  clearMap()
})
</script>

<style scoped>
.patrol-route {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.patrol-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 280px;
  max-height: calc(100vh - 40px);
  background: rgba(0, 0, 0, 0.9);
  border: 1px solid #52b788;
  border-radius: 8px;
  backdrop-filter: blur(10px);
  z-index: 200;
  color: #ffffff;
  font-size: 14px;
  pointer-events: auto;
  overflow-y: auto;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #52b788;
  display: flex;
  align-items: center;
  gap: 10px;
}

.panel-header h3 {
  margin: 0;
  color: #52b788;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  width: 20px;
  height: 20px;
  fill: #52b788;
}

.panel-content {
  padding: 15px;
}

.plan-selector {
  margin-bottom: 15px;
}

.plan-selector label {
  display: block;
  margin-bottom: 5px;
  color: #52b788;
  font-weight: 500;
}

.plan-selector select {
  width: 100%;
  padding: 8px;
  border: 1px solid #52b788;
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  font-size: 13px;
}

.plan-details {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.plan-info {
  padding: 15px;
  background: rgba(82, 183, 136, 0.1);
  border-radius: 6px;
  border: 1px solid rgba(82, 183, 136, 0.3);
}

.plan-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.plan-title h4 {
  margin: 0;
  color: #52b788;
  font-size: 16px;
}

.priority-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  color: #ffffff;
}

.plan-description {
  margin: 0 0 12px 0;
  color: #95d5b2;
  font-size: 13px;
  line-height: 1.4;
}

.plan-stats {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 10px;
}

.stat-item {
  text-align: center;
  padding: 8px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
}

.stat-label {
  font-size: 11px;
  color: #95d5b2;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 13px;
  font-weight: 600;
  color: #ffffff;
}

.checkpoints-list h5 {
  margin: 0 0 10px 0;
  color: #52b788;
  font-size: 14px;
}

.checkpoints-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.checkpoint-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 4px;
  border: 1px solid rgba(82, 183, 136, 0.2);
}

.checkpoint-number {
  width: 24px;
  height: 24px;
  background: #52b788;
  color: #ffffff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.checkpoint-info {
  flex: 1;
}

.checkpoint-name {
  font-size: 13px;
  color: #ffffff;
  font-weight: 500;
}

.checkpoint-type {
  font-size: 11px;
  color: #95d5b2;
}

/* 地图标记样式 */
:global(.checkpoint-marker) {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 2px solid #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
  color: #ffffff;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  position: relative;
  transform: scale(1);
  transition: transform 0.2s ease;
}

:global(.checkpoint-marker:hover) {
  transform: scale(1.1);
}

:global(.checkpoint-number-badge) {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 16px;
  height: 16px;
  background: #52b788;
  color: #ffffff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: 600;
  border: 1px solid #ffffff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
}

:global(.checkpoint-icon-badge) {
  font-size: 14px;
}

:global(.checkpoint-info-popup) {
  min-width: 200px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

:global(.popup-header) {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

:global(.popup-number) {
  width: 20px;
  height: 20px;
  background: #52b788;
  color: #ffffff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
}

:global(.popup-header h4) {
  margin: 0;
  font-size: 14px;
  color: #333;
}

:global(.popup-content p) {
  margin: 4px 0;
  font-size: 12px;
  color: #666;
}
</style>